﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Lucene;
using Lucene.Net.Index;
using IDBServices;
using SqlServices;
using Lucene.Net.Documents;
using System.Data;
using IServices.Extension;
using PanGu;
using PanGu.Framework;
using Lucene.Net.Analysis.PanGu;
using Quartz;
namespace LuceneNetServices
{
    public class Index
    {
        /// <summary>
        /// 创建索引
        /// </summary>
        /// <param name="autoCommit">是否自动提交 设置我ifalse可能极大提高效率</param>
        public void CreateIndex()
        {
            IndexWriter indexWriter = SingleIndexWriterFactory.GetSingleWriter();//采用唯一实例 
            Document doc = new Document();

            string sql = "select top 1000 title,blogContent,authorID,linkurl,publishTime from   blog";
            DataTable dtBlog = SqlHelper.ExecuteDataTable(sql, null);
            ///ToDo: 这样做会存在一个问题就是每次都需要读取全部数据 需要的时间会很长 尤其在数据量大的时候 需要解决
            ///为了尽可能的提高索引的速度 减少变量的创建数量 减轻GC负担
            if (dtBlog != null)
            {
                foreach (DataRow row in dtBlog.Rows)
                {
                    string title = MString.mTrim(row["title"]);
                    string blogContent = MString.mTrim(row["blogContent"]);
                    string linkUrl = MString.mTrim(row["linkUrl"]);
                    string authorID = MString.mTrim(row["authorID"]);
                    Field field = new Field("title", title, Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_OFFSETS);
                    field.SetBoost(2.0f);
                    field = new Field("content", blogContent, Field.Store.YES, Field.Index.ANALYZED);
                    doc.Add(field);
                    field = new Field("authorID", authorID, Field.Store.YES, Field.Index.NOT_ANALYZED);
                    doc.Add(field);
                    field = new Field("linkUrl", linkUrl, Field.Store.YES, Field.Index.NOT_ANALYZED);
                    doc.Add(field);
                    indexWriter.AddDocument(doc, new PanGuAnalyzer());
                }
                try
                {
                    indexWriter.Optimize(100);
                    indexWriter.PrepareCommit();
                    indexWriter.Commit();
                    indexWriter.Close();
                }
                catch (Exception ex)
                {
                    if (indexWriter != null)
                    {
                        indexWriter.Close();
                    }
                }
            }
        }


    }
}
